package com.zzx.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.boot.common.CustomException;
import com.zzx.boot.common.R;
import com.zzx.boot.mapper.CategoryMapper;
import com.zzx.boot.pojo.Category;
import com.zzx.boot.pojo.Dish;
import com.zzx.boot.pojo.DishFlavor;
import com.zzx.boot.pojo.Setmeal;
import com.zzx.boot.service.CategoryService;
import com.zzx.boot.service.DishService;
import com.zzx.boot.service.SetmealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper mapper;

    /*注入其他service层的对象*/
    @Resource
    private DishService dishService;//菜品
    @Resource
    private SetmealService setmealService;//套餐

    @Override
    public R<Page> selectPage(Integer page, Integer pageSize) {
        Page<Category> page1 = new Page(page,pageSize);

        IPage<Category> page2 = mapper.getPage(page1);
        if (page2!=null){
            return R.success(page1);
        }
        return R.error("查询失败");
    }

    @Override
    public R<String> remove(Long id) {
        //查询是否关联菜品
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(queryWrapper1);
        if (count1>0){
            throw new CustomException("当前分类关联的菜品,无法删除!");
        }
        //查询是否关联套餐
        LambdaQueryWrapper<Setmeal> queryWrapper2 = new LambdaQueryWrapper();
        queryWrapper2.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(queryWrapper2);
        if (count2>0){
            throw new CustomException("当前分类关联了套餐,无法删除!");
        }

        boolean b = removeById(id);

        return b?R.success("删除成功!"):R.error("删除失败");
    }

    @Override
    public List<Category> getTypeList(Integer type) {
        LambdaQueryWrapper<Category>wrapper = new LambdaQueryWrapper();
        wrapper.eq(Category::getType,type);
        List<Category> categories = mapper.selectList(wrapper);
        return categories;
    }
}
